//
//  QCSetupBottomCell.swift
//  爱汽车
//
//  Created by tucici on 2023/8/27.
//

import UIKit
import TCCKit
class QCSetupBottomCell: UITableViewCell {
    
    @IBOutlet var btn0: UIButton!
    @IBOutlet var btn1: UIButton!
    @IBOutlet var btn2: UIButton!
    @IBOutlet var btn3: UIButton!
    @IBOutlet var btn4: UIButton!
    ///排气
    @IBOutlet var exhaustBtn: UIButton!
    ///预制高度
    @IBOutlet var heightBtn: UIButton!
    ///历史警报
    @IBOutlet var warningBtn: UIButton!
    ///排水
    @IBOutlet var drainBtn: UIButton!
    ///故障
    @IBOutlet var errorBtn: UIButton!
    @IBOutlet var bg_error: UIView!
    ///34到40,6个字节的错误内容，如果有变化，就代表有新增
    private var errorMD5 = ""
    var array1 = [UIButton]()
    ///气缸气压当前值
    private var exhaustBtnValue = 0
    var block:((_ btn:UIButton)->Void)?
    override func awakeFromNib() {
        super.awakeFromNib()
        initUI()
    }
    
    func initUI(){
        btn1.bringSubviewToFront(btn1.titleLabel!)
        btn2.bringSubviewToFront(btn2.titleLabel!)
        btn3.bringSubviewToFront(btn3.titleLabel!)
        btn4.bringSubviewToFront(btn4.titleLabel!)
        
        array1 = [btn0,btn1,btn2,btn3,btn4]
        let long = UILongPressGestureRecognizer(target: self, action: #selector(actionForlongPress))
        long.minimumPressDuration = 2
        btn0.addGestureRecognizer(long)
        /*for btn in array1{
         btn.setTitleColor("#FF5100".color(0.6), for: .selected)
         }*/
    }
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
        // Configure the view for the selected state
    }
    var bytes = [UInt8](){
        didSet{
            guard bytes.count >= 8 else{return}
            let ack = bytes[7]
            let data = [UInt8](bytes[AI_index..<bytes.count])
            switch ack{
            case UInt8(AIQC.infoStatus.ack):
                let errors = [Int(data[31]),Int(data[32]),Int(data[33]),Int(data[34]),Int(data[35]),Int(data[36])]
                QCErrorController.jude(errors,{[weak self] result in
                    let md5 = (result.map{String(format: "%@", $0)}.joined() as NSString).md5 as String
                    if self?.errorMD5 != md5 {
                        self?.errorMD5 = md5
                        self?.bg_error.isHidden = errors.reduce(0, {$0+$1}) <= 0
                        self?.warningBtn.isSelected = !(self?.bg_error.isHidden ?? true)
                        
                        ///15秒自动消失，
                        if self?.bg_error.isHidden == false{
                            let title = result.count > 0 ? result[0] : "系统故障"
                            self?.errorBtn.setTitle(LS(title), for: .normal)
                            DispatchQueue.main.asyncAfter(deadline: .now()+15, execute: {[weak self] in
                                ///有一版本，有报警时。此时应该为红色，15s后自动消除。
                                //                            self?.bg_error.isHidden = true
                                //                            self?.warningBtn.isSelected = false
                                ///后又有一版本 ，改为：有报警且未消除时，铃铛为白色。此时应该为红色，直至报警消除，或手动清除。所以注释掉上面的
                            })
                        }
                    }
                })
                
                
                ///当前档位处于预置位位置，档位按钮的高亮状态
                let bit = Int(data[2])
                let dangwei = bit & 0xF///Bit0~bit3: 0:手动位置, 1~5:档位1~5
                setBtn(dangwei)
                //                if dangwei > 0{
                //                    let sender : UIButton = dangwei > array1.count ? btn0 : array1[dangwei - 1]
                //                    if dangwei < 5 {
                //                        setBtn(btn0, sender)
                //                    }
                //                    for btn in array1{
                //                        setBtn(btn, sender)
                //                    }
                //                }
                
                exhaustBtnValue = Int(data[7])///气缸气压当前
                
            case UInt8(AIQC.userInfo.ack):
                ///如果手动打气是打气状态(按钮高亮状态)，根据气缸气压的当前值 >=气缸气压的上限,，则手动停止打气
                if exhaustBtn.isSelected && (exhaustBtnValue >= Int(data[87])){
                    //exhaustBtn.isSelected = false
                    actionForBtn(exhaustBtn)
                }
                
                //                ///水平静止状态下超过5S,自动预置位调节还是使能状态，则要设置为
                //                heightBtn.isSelected = Int(data[87]) == 1
                //                if heightBtn.isSelected && Int(data[87]) == 1{
                //                    actionForBtn(heightBtn)
                //                }
            default:
                break
            }
        }
    }
    
    @IBAction func actionForBtn(_ sender: UIButton) {
        if array1.contains(sender){
            for i in 0..<array1.count{
                if sender != btn0 && sender != array1[i]{continue}
                setBtn(sender == btn0 ? 5 : i)
                NotificationCenter.default.post(name:NSNotification.Name("updateDangwei"), object:nil)
            }
        }else if sender == drainBtn{
            sender.isSelected = !sender.isSelected
            ///15000ms ,每次点击倒计时，到了变灰
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
                sender.isSelected = false
            }
        }else if sender != warningBtn{
            sender.isSelected = !sender.isSelected
        }
        block?(sender)
    }
    
    @objc func actionForlongPress(sender: UILongPressGestureRecognizer){
        guard let btn = sender.view as? UIButton, btn == btn0 else{return}
        if sender.state == .began{
            setBtn(5)
            block?(btn)
        }else if sender.state == .ended{
            //  block?(btn)
        }
    }
    
    private func setBtn(_ dangwei:Int){
        if array1.count < dangwei {return}
        let sender = dangwei == 0 ? UIButton() : array1[dangwei == 5 ? 0 : dangwei]
        for btn in array1{
            btn.isSelected = btn.tag == sender.tag
            if btn.currentTitle ?? "" == "" {continue}
            let num = (btn.currentTitle ?? "0").intValue()
            let colors = btn.isSelected ? ["#FD6E36".color(),"#FDED99".color()] : ["#FFFFFF".color(),"#FFFFFF".color()]
            let font = btn.isSelected ? UIFont(name: "Lato-Bold", size: 39)! : UIFont(name: "Lato-Regular", size: 34)!
            attrText(num: num, colors: colors, font: font,btn: btn)
        }
    }
    
    private func attrText(num:Int, colors:[UIColor], font:UIFont,  btn:UIButton){
        let attr = "\(num)".setGradientText(colors: colors, bounds: btn.bounds, font:font)
        btn.setAttributedTitle(attr, for: .normal)
        btn.titleLabel?.sizeToFit()
        btn.titleEdgeInsets = btn.isSelected ? UIEdgeInsets(top: 0, left:-btn.bounds.width+btn.titleLabel!.bounds.width-4, bottom: 0, right:btn.titleLabel!.bounds.width-4) : .zero
    }
}
